const express = require('express');
const router = express.Router();
const balanceRecordMod = require('../db/balanceRecordMod');
const { adminName } = require('../serverOpt');
const debug = require('debug')('a-sokio-yun:server');

// 获取余额记录列表
router.get('/list', async function (req, res) {
    const { userName, userId } = req.session;
    if (!userName || !userId) {
        return res.json({ code: -1, msg: '请先登录' });
    }

    try {
        const query = req.query;
        let searchCondition = {};

        // 非管理员只能看自己的余额记录
        if (userName !== adminName) {
            searchCondition.userId = userId;
        }

        // 删除标记过滤：只有cjroot管理员可以看到已删除记录
        if (userName !== 'cjroot') {
            searchCondition.isDeleted = { $ne: true };
        } else {
            // cjroot管理员可以通过isDeleted参数筛选记录状态
            if (query.isDeleted !== undefined && query.isDeleted !== '') {
                searchCondition.isDeleted = query.isDeleted === 'true';
            }
        }

        // 查询条件
        if (query.userId) {
            searchCondition.userId = query.userId;
        } else if (query.userName) {
            // 通过用户名查询，需要先查找用户ID
            const userMod = require('../db/userMod');
            const users = await userMod.find({ userName: { $regex: query.userName, $options: 'i' } }, '_id');
            if (users.length > 0) {
                const userIds = users.map(user => user._id);
                searchCondition.userId = { $in: userIds };
            } else {
                // 如果没有找到匹配的用户，返回空结果
                return res.json({ code: 0, msg: '', count: 0, data: [] });
            }
        }
        if (query.transactionType) {
            searchCondition.transactionType = query.transactionType;
        }
        if (query.operator) {
            searchCondition.operator = { $regex: query.operator, $options: 'i' };
        }
        if (query.remark) {
            searchCondition.remark = { $regex: query.remark, $options: 'i' };
        }
        if (query.orderNumber) {
            searchCondition.orderNumber = { $regex: query.orderNumber, $options: 'i' };
        }
        
        // 时间范围查询
        if (query.startTime && query.endTime) {
            searchCondition.createTime = {
                $gte: new Date(query.startTime),
                $lte: new Date(query.endTime)
            };
        }

        const page = parseInt(query.page) || 1;
        const limit = parseInt(query.limit) || 10;
        const skip = (page - 1) * limit;

        const total = await balanceRecordMod.countDocuments(searchCondition);
        const records = await balanceRecordMod.find(searchCondition)
            .populate('userId', 'userName')
            .sort({ createTime: -1 })
            .skip(skip)
            .limit(limit);

        res.json({
            code: 0,
            msg: '',
            count: total,
            data: records
        });
    } catch (error) {
        debug('获取余额记录列表错误:', error);
        res.json({ code: -1, msg: '获取余额记录失败' });
    }
});

// 更新余额记录备注
router.put('/update/:id', async function (req, res) {
    const { userName, userId } = req.session;
    if (!userName || !userId) {
        return res.json({ code: -1, msg: '请先登录' });
    }

    // 只有cjroot管理员可以修改备注
    if (userName !== 'cjroot') {
        return res.json({ code: -1, msg: '权限不足，无法修改备注' });
    }

    try {
        const { id } = req.params;
        const { remark } = req.body;
        
        const record = await balanceRecordMod.findByIdAndUpdate(id, {
            remark: remark || '',
            updateTime: new Date()
        }, { new: true });

        if (!record) {
            return res.json({ code: -1, msg: '记录不存在' });
        }

        res.json({ code: 0, msg: '备注修改成功', data: record });
    } catch (error) {
        debug('更新余额记录备注错误:', error);
        res.json({ code: -1, msg: '备注修改失败' });
    }
});

// 删除余额记录（软删除）
router.delete('/delete/:id', async function (req, res) {
    const { userName, userId } = req.session;
    if (!userName || !userId) {
        return res.json({ code: -1, msg: '请先登录' });
    }

    // 只有cjroot管理员可以删除
    if (userName !== 'cjroot') {
        return res.json({ code: -1, msg: '权限不足，无法删除记录' });
    }

    try {
        const { id } = req.params;
        const record = await balanceRecordMod.findByIdAndUpdate(
            id, 
            { isDeleted: true }, 
            { new: true }
        );
        
        if (!record) {
            return res.json({ code: -1, msg: '记录不存在' });
        }

        res.json({ code: 0, msg: '删除成功' });
    } catch (error) {
        debug('删除余额记录错误:', error);
        res.json({ code: -1, msg: '删除失败' });
    }
});

// 批量删除余额记录（软删除）
router.post('/deleteMultiple', async function (req, res) {
    const { userName, userId } = req.session;
    if (!userName || !userId) {
        return res.json({ code: -1, msg: '请先登录' });
    }

    // 只有cjroot管理员可以删除
    if (userName !== 'cjroot') {
        return res.json({ code: -1, msg: '权限不足，无法删除记录' });
    }

    try {
        const { ids } = req.body;
        
        if (!ids || !Array.isArray(ids) || ids.length === 0) {
            return res.json({ code: -1, msg: '请选择要删除的记录' });
        }

        await balanceRecordMod.updateMany(
            { _id: { $in: ids } },
            { isDeleted: true }
        );
        
        res.json({ code: 0, msg: '批量删除成功' });
    } catch (error) {
        debug('批量删除余额记录错误:', error);
        res.json({ code: -1, msg: '批量删除失败' });
    }
});

module.exports = router;